package net.wanglu.www.zzz.rule.artcl;

import java.util.regex.Pattern;

import net.wanglu.www.zzz.rule.BadEgg;
import net.wanglu.www.zzz.rule.Rule;
import net.wanglu.www.zzz.service.se.np._NPTuple;
import edu.stanford.nlp.ling.TaggedWord;
import edu.stanford.nlp.trees.Tree;
import edu.stanford.nlp.trees.tregex.TregexMatcher;
import edu.stanford.nlp.trees.tregex.TregexPattern;

public class Vowel extends _ArticleRule {

	Pattern vowel = Pattern.compile("^[aeiou]");
	
	@Override
	public Object applicable(Object... objects) throws Exception {
		// TODO Auto-generated method stub
		_NPTuple npt = (_NPTuple) objects[1];
		Tree NP = npt.getNP();
		if ( NP.depth() != 2) return Rule.Inapplicable;//如果不是叶子节点的父母则不符合要求
		TaggedWord headword = npt.getHeadword();
		if ( "NN".equals(headword.tag()) || "NNP".equals(headword.tag())) {
			return Rule.Applicable;//如果中心词是名词则符合要求，否则不符合
		} else {
			return Rule.Inapplicable;
		}
	}

	@Override
	public Object deviseRightSolution(Object... objects) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object examine(Object... objects) throws Exception {
		// TODO Auto-generated method stub
		if ( this.applicable(objects) == Rule.Inapplicable) return Rule.Inapplicable;
		
		_NPTuple npt = (_NPTuple) objects[1];
		Tree NP = npt.getNP();

		TregexPattern pattern = null;
		TregexMatcher matcher = null;
		/*
		 * 冠词本身
		 */
		Tree dt = null;
		sb.clear();
		sb.append("(/\\bDT\\b/</\\b[Aa]n?\\b/)");
		pattern = TregexPattern.compile(sb.toString());
		matcher = pattern.matcher(NP);
		if ( matcher.find()) {
			dt = matcher.getMatch();
		} else {
			return Rule.Inapplicable;
		}
		/*
		 * 紧挨冠词右边的单词
		 */
		Tree right = null;
		sb.clear();
		sb.append("/\\w+/");
		sb.append(",");
		sb.append("(/\\bDT\\b/</\\b[Aa]n?\\b/)");
		pattern = TregexPattern.compile(sb.toString());
		matcher = pattern.matcher(NP);
		if ( matcher.find()) {
			right = matcher.getMatch();
		}
		String rightWord = right.taggedYield().get(0).word();

		String dtWord = dt.taggedYield().get(0).word();

		if ( "a".equalsIgnoreCase(dtWord)) {
			if ( vowel.matcher(rightWord).find()) {
				BadEgg egg = new BadEgg();
				egg.whereIsWrong = NP;
				egg.setProperty(BadEgg.Error);
				egg.setViolatedRule(this);
				return egg;
			}
		} else if ( "an".equalsIgnoreCase(dtWord)) {
			if ( !vowel.matcher(rightWord).find()) {
				BadEgg egg = new BadEgg();
				egg.whereIsWrong = NP;
				egg.setProperty(BadEgg.Error);
				egg.setViolatedRule(this);
				return egg;
			}
		}
		return null;
	}

	@Override
	public Object whyItsWrong(Object... objects) throws Exception {
		// TODO Auto-generated method stub
		sb.clear();
		sb.append("<p>");
		sb.append("不定冠词a用在辅音开头前，an用在元音开头前。");
		sb.append("</p>");			
		return sb.toString();
	}
}
